package extractorCode;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class link5 {
	
	private final static int INITIAL_BUF_SIZE = 65536;
	public static void main(String args[]) throws Exception
	{
	
		int count=0;
	    boolean nextIndex=true;
	    BufferedReader reader= new BufferedReader(new FileReader("c:\\keywords-link5-edited.txt"));
	    
	    
	    String keyword;
	    while((keyword=reader.readLine())!=null)
	    {
	    	count=0;
	    	String[] splitarr=keyword.split("\t");
	    	String key = splitarr[0];
	    	int maxPage=Integer.parseInt(splitarr[1]);
	    	System.out.println(keyword);
	       if(maxPage>-1)
	       {
	    	BufferedWriter wr = new BufferedWriter( new FileWriter("C:\\newData2\\link5-"+key+"-withDate.txt"));
		for(int i=0;i<=maxPage;i++)
		{	
			Thread.sleep(10000);
		System.out.println("page"+i);	
		String page = (fetchPage("http://www.google.com/custom?hl=id&client=google-coop&cof=FORID:11%3BAH:left%3BCX:Suara%2520Merdeka%3BL:http://www.google.com/intl/id/images/logos/custom_search_logo_sm.gif%3BLH:30%3BLP:1%3BVLC:%23551a8b%3BDIV:%23cccccc%3B&cx=011105698729379298933:xjdh4rvhmf4&ad=n9&adkw=AELymgVYg9vthoQJ0wLB92ZcIc1yjcR8hFpCqqjQblsPrTct78EESBSGqR_jlDut2Rn-qG7MlYb9ANcr6gRuaEX2rKMbzOY-U_HXW5yDe2SmHJ7gyT30uae2eK1L9rV_E1B1z3mEOD5zOVKnNzyqWB3B1mZ3NmVDoyiAOf5Qcm0PtFNAMslvAJ14Mn0Y7A1xfy9Cr3YDEue_6wn2_txsTWDCOxrqi3s0Vw&boostcse=0&ei=4KfiTuOGOuGmiQKF0ZnGBg&q="+key+"&start="+(i*10)+"&sa=N"));
		System.out.println(page);
		Matcher dateItem = Pattern.compile("<span class=\"s\">(.*?)<b>", Pattern.CASE_INSENSITIVE).matcher( page );
		Matcher titleItem = Pattern.compile("<a class=\"l\".*?>(.*?)</a>", Pattern.CASE_INSENSITIVE).matcher( page );
		
		
		
		page= page.replaceAll(">\\s*<", "><");
		
		page = page.replaceAll("\t", "");
		page = page.replaceAll("\b", "");
		page = page.replaceAll("\r", "");
		page = page.replaceAll("\n", "");
		page = page.replaceAll("\r\n", "");
		Matcher newsItem = Pattern.compile("<a class=\"l\"\\s*(href=\"(.*?)\")", Pattern.CASE_INSENSITIVE).matcher( page );
			
		
	while(newsItem.find()&& dateItem.find()&&titleItem.find())
		{
	//	System.out.println(newsItem.group(1));
		
		String text = newsItem.group(1);
		String date= dateItem.group(1);
		String title= titleItem.group(1);
		nextIndex= text.contains("<span>Next</span>");
		System.out.println(text+" "+date);
		text = text.replaceAll("\\<.*?>","");
		text = text.replaceAll("[^\\p{ASCII}]", "");
		
		title = title.replaceAll("\\<.*?>","");
		title = title.replaceAll("[^\\p{ASCII}]", "");
		wr.write(text+","+date+","+title+"\n");
		System.out.println(text+"\t"+date);
	
		count++;
		//System.out.println(text);
	//	writer.write("http://newsbusters.org"+newsItem.group(1)+"\n");
		}
		}
		System.out.println("The total number of links "+count);
		wr.close();
	       }
	    }
	}
	
	private static String fetchPage(String urlString){
		StringBuilder buffer = new StringBuilder(INITIAL_BUF_SIZE);
		try {
			//URL url = new URL( urlString );
			
			
			 URL url = new URL(urlString);
             HttpURLConnection.setFollowRedirects(false);
             HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();

            //urlConn.setRequestProperty("User-agent","Mozilla/7.0.1");
             urlConn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2");
             urlConn.connect();
             BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
             
			
			//BufferedInputStream reader = new BufferedInputStream(url.openStream());
			int temp = reader.read();
			while(temp != -1){
				buffer.append((char)temp);
				temp = reader.read();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buffer.toString();
	}

}
